<template>
  <view class="container">
    <!-- <text class="time">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</text> -->
    <slider 
      :value="progressPercent" 
      @change="handleProgressChange"
      min="0" max="100"
      activeColor="#FF4949" 
      backgroundColor="#eee"
    />

<!--    <view class="controls">
      <button @click="playOrPause">{{ isPlaying ? '暂停' : '播放' }}</button>
    </view> -->
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineExpose} from 'vue';

const props = defineProps({
	url: {
		type:String,
		default: '',
	}
})

const emits = defineEmits(['play'])

let audioCtx = null;
const isPlaying = ref(false);
const duration = ref(0);
const currentTime = ref(0);
const progressPercent = ref(0);

function initAudio() {
  audioCtx = uni.createInnerAudioContext();
  audioCtx.src = props.url // 音乐路径

  // 监听可以播放
  audioCtx.onCanplay(() => {
    console.log('可以播放');
    audioCtx.play(); // 可以自动播放
    isPlaying.value = true;
  });

  // 获取总时长
  audioCtx.onPlay(() => {
    isPlaying.value = true;
    duration.value = Math.floor(audioCtx.duration);
  });

  // 监听播放时间更新
  audioCtx.onTimeUpdate(() => {
    currentTime.value = Math.floor(audioCtx.currentTime);
    progressPercent.value = (currentTime.value / duration.value) * 100;
  });

  // 监听自然结束
  audioCtx.onEnded(() => {
    isPlaying.value = false;
    // 可以在这里添加播放下一首逻辑
  });
}

function playOrPause() {
  if (isPlaying.value) {
    audioCtx.pause();
  } else {
    audioCtx.play();
  }
  isPlaying.value = !isPlaying.value;
}

// 格式化时间（秒 -> mm:ss）
function formatTime(seconds) {
  const min = Math.floor(seconds / 60).toString().padStart(2, '0');
  const sec = (seconds % 60).toString().padStart(2, '0');
  return `${min}:${sec}`;
}

function handleProgressChange(e) {
  const percent = e.detail.value;
  const newTime = (percent / 100) * duration.value;
  audioCtx.seek(newTime);
}

onMounted(() => {
  initAudio();
});

onUnmounted(() => {
  // 页面卸载时销毁音频
  if (audioCtx) {
    audioCtx.stop();
    audioCtx.destroy();
  }
});

// defineExpose(['playOrPause'])
</script>

<style scoped>
.container {
  padding: 40rpx;
  text-align: center;
}
.title {
  font-size: 36rpx;
  margin-bottom: 40rpx;
  display: block;
}
.time {
  margin: 20rpx 0;
  display: block;
  font-size: 28rpx;
  color: #666;
}
.controls {
  margin-top: 50rpx;
}
</style>